import App from './App'
import api from '@/api'
import http from '@/api/http'

// 请求拦截器
http.setRequestInterceptor(async (config) => {
  // 添加 token
  const token = uni.getStorageSync('user_token')
  if (token) {
    config.header['Authorization'] = `Bearer ${token}`
    config.header['user_token'] = `${token}`
  }
  return config
})

// 响应拦截器
http.setResponseInterceptor(async (response) => {
  const { statusCode, data } = response
  if (data.code === 200) {
    return data
  } else if (data.code === 401) {
    // token 过期处理
    uni.navigateTo({ url: '/pages/login/login' })
    throw new Error('未授权，请重新登录')
  } else if (data.code === 402) {
    // 跳转到对应页面
    uni.navigateTo({ url: data.data.redirect_url })
    throw new Error(data.msg)
  } else {
    throw new Error(data.msg || '请求失败')
  }
})
// 全局挂载api
uni.$api = api;
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
import uViewPlus from '@/uni_modules/uview-plus'
Vue.config.productionTip = false
App.mpType = 'app'
Vue.use(uViewPlus)
const app = new Vue({
  ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
import uViewPlus from '@/uni_modules/uview-plus'

export function createApp() {
  const app = createSSRApp(App)
  app.use(uViewPlus)
  return {
    app
  }
}
// #endif